import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { RequireLoginKey } from 'src/cu-dec';
import { JwtService } from '@nestjs/jwt';

declare module 'express' {
  interface Request {
    user?: { username: string; id: number };
  }
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly jwtService: JwtService,
  ) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const requireLogin = this.reflector.getAllAndOverride(RequireLoginKey, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requireLogin) return true;

    const token = request.headers.authorization;

    if (!token) throw new UnauthorizedException('Token is required');

    try {
      const data = this.jwtService.verify(token);
      console.log(data);
      request.user = data;
      return true;
    } catch (error) {
      throw new UnauthorizedException('Token is invalid');
    }
  }
}
